"use client";
import { Button, Form, Input, Select, message, Space } from "antd";
import React, { useState } from "react";
import { editUserUsingPost } from "@/api/userController";
import { useSelector, useDispatch } from "react-redux";
import { RootState } from "@/stores";
import { setLoginUser } from "@/stores/loginUser";
import "./index.css";

const { Option } = Select;
const { TextArea } = Input;

interface Props {
  onCancel: () => void;
  onSuccess: () => void;
}

/**
 * 用户信息编辑表单组件
 */
const UserEditForm: React.FC<Props> = (props) => {
  const { onCancel, onSuccess } = props;
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const dispatch = useDispatch();

  // 获取当前用户信息
  const loginUser = useSelector((state:RootState)=>state.loginUser);

  // 年级选项
  const gradeOptions = [
    "大一", "大二", "大三", "大四", "研一",
    "研二", "研三", "博一", "博二",
    "博三", "博四", "已毕业", "在职",
  ];

  // 擅长方向选项
  const expertiseOptions = [
    "前端开发", "后端开发",
    "全栈开发", "移动开发", "算法与数据结构", "机器学习",
    "人工智能", "数据科学",
    "网络安全", "云计算",
    "DevOps", "测试", "产品设计", "UI/UX设计",
    "项目管理", "其他",
  ];

  // 表单提交处理
  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const response = await editUserUsingPost(values);
      if (response.code === 0) {
        message.success("个人信息更新成功！");
        // 更新Redux中的用户信息
        dispatch(
          setLoginUser({
            ...loginUser,
            ...values,
          }),
        );
        onSuccess();
      } else {
        message.error(response.message || "更新失败，请重试");
      }
    } catch (error: any) {
      console.error("用户信息更新失败:", error);
      message.error("更新失败：" + (error.message || "网络错误"));
    } finally {
      setLoading(false);
    }
  };

  // 取消编辑处理
  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <div
      className="user-edit-form"
      style={{
        padding: "24px",
      }}
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          userName: loginUser.userName,
          userProfile: loginUser.userProfile,
          phoneNumber: loginUser.phoneNumber,
          email: loginUser.email,
          grade: loginUser.grade,
          workExperience: loginUser.workExperience,
          expertiseDirection: loginUser.expertiseDirection,
        }}
        onFinish={handleSubmit}
      >
        <Form.Item
          label="用户名"
          name="userName"
          rules={[
            { required: true, message: "请输入用户名" },
            { min: 2, max: 20, message: "用户名长度为2-20个字符" },
          ]}
        >
          <Input placeholder="请输入用户名" />
        </Form.Item>

        <Form.Item
          label="个人简介"
          name="userProfile"
          rules={[{ max: 200, message: "个人简介不能超过200个字符" }]}
        >
          <TextArea
            rows={3}
            placeholder="请输入个人简介"
            showCount
            maxLength={200}
          />
        </Form.Item>

        <Form.Item
          label="手机号"
          name="phoneNumber"
          rules={[{ pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" }]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>

        <Form.Item
          label="邮箱"
          name="email"
          rules={[{ type: "email", message: "请输入正确的邮箱地址" }]}
        >
          <Input placeholder="请输入邮箱" />
        </Form.Item>

        <Form.Item label="年级" name="grade">
          <Select placeholder="请选择年级" allowClear>
            {gradeOptions.map((grade) => (
              <Option key={grade} value={grade}>
                {grade}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="工作经验"
          name="workExperience"
          rules={[{ max: 500, message: "工作经验描述不能超过500个字符" }]}
        >
          <TextArea
            rows={4}
            placeholder="请描述你的工作经验"
            showCount
            maxLength={500}
          />
        </Form.Item>

        <Form.Item label="擅长方向" name="expertiseDirection">
          <Select placeholder="请选择擅长方向" allowClear>
            {expertiseOptions.map((expertise) => (
              <Option key={expertise} value={expertise}>
                {expertise}
              </Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item>
          <Space>
            <Button type="primary" htmlType="submit" loading={loading}>
              保存修改
            </Button>
            <Button onClick={handleCancel}>取消</Button>
          </Space>
        </Form.Item>
      </Form>
    </div>
  );
};

export default UserEditForm;
